<template>
  <!-- 导航栏 -->
  <header id="navbar" class="fixed w-full z-50 transition-all duration-300">
    <div class="bg-white/95 backdrop-blur-sm shadow-sm">
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <!-- Logo -->
          <div class="flex items-center">
            <a href="#" class="flex items-center">
              <i class="fa fa-music text-primary text-2xl mr-2"></i>
              <span class="text-xl font-bold text-primary">初练音乐</span>
            </a>
          </div>

          <!-- 导航链接 - 桌面端 -->
          <nav class="hidden md:flex space-x-8">
            <a
              href="#"
              class="text-dark hover:text-primary font-medium transition-colors"
              >首页</a
            >
            <a
              href="#categories"
              class="text-dark hover:text-primary font-medium transition-colors"
              >乐谱分类</a
            >
            <a
              href="#featured"
              class="text-dark hover:text-primary font-medium transition-colors"
              >热门推荐</a
            >
            <a
              href="#about"
              class="text-dark hover:text-primary font-medium transition-colors"
              >关于我们</a
            >
          </nav>

          <!-- 右侧功能区 -->
          <div class="flex items-center space-x-4">
            <button
              id="searchBtn"
              class="p-2 rounded-full hover:bg-gray-100 transition-colors"
              @click="toggleSearch"
            >
              <i class="fa fa-search text-neutral"></i>
            </button>
            <button
              v-if="!token"
              id="userBtn"
              class="p-2 rounded-full hover:bg-gray-100 transition-colors"
              @click="() => toggleAuthModal(true)"
            >
              <i class="fa fa-user text-neutral"></i>
            </button>
            <el-dropdown
              v-if="token"
              class="p-2 rounded-full hover:bg-gray-100 transition-colors"
              trigger="click"
            >
              <el-image
                class="w-8 h-8 rounded-full object-cover"
                fit="cover"
                :src="attachImageUrl(userPic)"
              />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.stop="logOut"
                    >退出登录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <button
              id="mobileMenuBtn"
              class="md:hidden p-2 rounded-full hover:bg-gray-100 transition-colors"
            >
              <i class="fa fa-bars text-neutral"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索框 -->
    <div
      id="searchBox"
      :class="hidden ? 'hidden' : ''"
      class="bg-white border-t border-gray-200 py-4"
    >
      <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="relative">
          <input
            type="text"
            placeholder="搜索乐谱、乐器或作曲家..."
            class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"
          />
          <i
            class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"
          ></i>
        </div>
      </div>
    </div>

    <!-- 移动端菜单 -->
    <div
      id="mobileMenu"
      class="hidden md:hidden bg-white border-t border-gray-200"
    >
      <div class="container mx-auto px-4 py-3">
        <nav class="flex flex-col space-y-3">
          <a
            href="#"
            class="text-dark hover:text-primary font-medium py-2 transition-colors"
            >首页</a
          >
          <a
            href="#categories"
            class="text-dark hover:text-primary font-medium py-2 transition-colors"
            >乐谱分类</a
          >
          <a
            href="#featured"
            class="text-dark hover:text-primary font-medium py-2 transition-colors"
            >热门推荐</a
          >
          <a
            href="#about"
            class="text-dark hover:text-primary font-medium py-2 transition-colors"
            >关于我们</a
          >
        </nav>
      </div>
    </div>
    <!-- 登录/注册模态框 -->
    <div
      v-if="showAuthModal"
      id="authModal"
      class="fixed inset-0 z-50 flex items-center justify-center"
    >
      <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
      <div
        class="relative bg-white rounded-xl shadow-2xl w-full max-w-md mx-4 transform transition-all"
      >
        <div class="flex justify-end p-4">
          <button
            id="closeAuthModal"
            class="p-2 rounded-full hover:bg-gray-100 transition-colors"
            @click="() => toggleAuthModal(false)"
          >
            <i class="fa fa-times text-neutral"></i>
          </button>
        </div>

        <div class="p-6">
          <!-- 标签页切换 -->
          <div class="flex border-b">
            <button
              class="flex-1 py-3 text-lg font-medium transition-colors"
              :class="
                isLoginTabActive
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-neutral hover:text-dark'
              "
              @click="switchToLoginFun"
              >登录</button
            >
            <button
              class="flex-1 py-3 text-lg font-medium transition-colors"
              :class="
                isRegisterTabActive
                  ? 'text-primary border-b-2 border-primary'
                  : 'text-neutral hover:text-dark'
              "
              @click="switchToRegisterFun"
              >注册</button
            >
          </div>

          <!-- 登录表单 -->
          <div v-if="isShowLoginForm" class="login-form">
            <el-form
              ref="signInForm"
              status-icon
              :model="loginForm"
              :rules="SignInRules"
              label-position="top"
            >
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="loginForm.username"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                ></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                ></el-input>
                <div class="flex justify-end mt-1">
                  <el-link type="primary" :underline="false" class="text-xs"
                    >忘记密码?</el-link
                  >
                </div>
              </el-form-item>
              <el-button type="primary" class="w-full" @click="handleLogin"
                >登录</el-button
              >
            </el-form>
            <div class="switch-form mt-4 text-center">
              <p
                >还没有账号?
                <el-link type="primary" @click="switchToRegisterFun"
                  >立即注册</el-link
                ></p
              >
            </div>
          </div>

          <!-- 注册表单 -->
          <div v-if="isShowRegisterForm" class="register-form">
            <el-form
              ref="signUpForm"
              status-icon
              :rules="SignUpRules"
              :model="registerForm"
              label-position="top"
            >
              <el-form-item label="姓名" prop="username">
                <el-input
                  v-model="registerForm.username"
                  placeholder="请输入姓名"
                  :prefix-icon="User"
                ></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="registerForm.sex">
                  <el-radio :label="0">女</el-radio>
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">保密</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="registerForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  show-password
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="registerForm.agreement">
                  我已阅读并同意<el-link type="primary">用户协议</el-link
                  >和<el-link type="primary">隐私政策</el-link>
                </el-checkbox>
              </el-form-item>
              <el-button type="primary" class="w-full" @click="handleRegister"
                >注册</el-button
              >
            </el-form>
            <div class="switch-form mt-4 text-center">
              <p
                >已有账号?
                <el-link type="primary" @click="switchToLoginFun"
                  >立即登录</el-link
                ></p
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>
</template>

<script lang="ts" setup>
  import { Lock, User } from '@element-plus/icons-vue';
  import { SignInRules, SignUpRules } from '@/enums';
  import { ref, reactive, computed, getCurrentInstance } from 'vue';
  import { ElMessage } from 'element-plus';
  import HttpManager from '@/api';
  import { ResponseBody } from '@/types';
  import { useStore } from 'vuex';

  const { attachImageUrl } = HttpManager;
  const store = useStore();
  const token = computed(() => store.getters.token);
  const { proxy } = getCurrentInstance() as any;
  const logOut = () => {
    // 去除token; 回到首页
    proxy.$store.commit('setToken', false);
    ElMessage.success('退出登录成功');
  };
  // 搜索框的代码
  const hidden = ref(true);
  const toggleSearch = () => {
    hidden.value = !hidden.value;
  };

  // 登录/注册模态框
  const showAuthModal = ref(false);
  const toggleAuthModal = (value: boolean) => {
    showAuthModal.value = value;
    document.body.style.overflow = value ? 'hidden' : '';
  };

  // 使用响应式数据控制表单显示和标签页样式
  const isShowLoginForm = ref(true);
  const isShowRegisterForm = ref(false);
  const isLoginTabActive = ref(true);
  const isRegisterTabActive = ref(false);

  // 登录表单数据
  const loginForm = reactive({
    username: '',
    password: '',
  });

  const signInForm = ref();
  // 处理登录
  const handleLogin = async () => {
    let canRun = true;
    signInForm.value.validate((valid: any) => {
      if (!valid) canRun = false;
    });
    if (!canRun) return;
    const { username } = loginForm;
    const { password } = loginForm;
    const result = (await HttpManager.signIn({
      username,
      password,
    })) as ResponseBody;
    ElMessage({
      message: result.message,
      type: result.type as any,
    });

    if (result.success) {
      proxy.$store.commit('setUserId', result.data[0].id);
      proxy.$store.commit('setUsername', result.data[0].username);
      proxy.$store.commit('setUserPic', result.data[0].avator);
      proxy.$store.commit('setToken', true);
      toggleAuthModal(false);
    }
  };

  const switchToRegisterFun = () => {
    isShowLoginForm.value = false;
    isShowRegisterForm.value = true;
    isLoginTabActive.value = false;
    isRegisterTabActive.value = true;
  };

  // 切换到登录表单
  const switchToLoginFun = () => {
    isShowLoginForm.value = true;
    isShowRegisterForm.value = false;
    isLoginTabActive.value = true;
    isRegisterTabActive.value = false;
  };
  const signUpForm = ref();
  // 注册表单数据
  const registerForm = reactive({
    username: '',
    sex: '',
    password: '',
    agreement: false,
  });
  // 处理注册
  const handleRegister = async () => {
    if (!registerForm.agreement) {
      ElMessage.warning('请阅读并同意用户协议和隐私政策');
      return;
    }
    let canRun = true;
    await signUpForm.value.validate((valid: any) => {
      if (!valid) canRun = false;
    });
    if (!canRun) return;
    console.log('-----canRun', canRun);
    const { username, password, sex } = registerForm;
    const result = (await HttpManager.SignUp({
      username,
      password,
      sex,
    })) as ResponseBody;
    ElMessage({
      message: result.message,
      type: result.type as any,
    });
    if (result.success) {
      switchToLoginFun();
      // toggleAuthModal(false);
    }
  };

  // 切换到注册表单
</script>

<style lang="less"></style>
